package cn.edu.scau.cmil.linwei.comprehensive.Controller;

import cn.edu.scau.cmil.linwei.comprehensive.Script.*;
import cn.edu.scau.cmil.linwei.comprehensive.util.DataIO;
import cn.edu.scau.cmil.linwei.comprehensive.util.StageManager;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;


import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;

public class RegisterController implements Initializable {


    public BorderPane borderPane;
    public ComboBox userKindComboBox;
    public ComboBox gradeComboBox;
    public ComboBox majorComboBox;
    public ComboBox classComboBox;
    public Pane usuallypane;
    public Pane extrapane;
    public Label usuallyTipText;
    public Label extraTipText;
    public TextField IDInputTextField;
    public TextField PWInputTextField;
    public TextField NameInputTextField;
    public TextField IQInputTextField;
    public TextField IAInputTextField;


    public void InituserKindComboBox(){
        userKindComboBox.getItems().add("学生");
        userKindComboBox.getItems().add("教师");
    }//初始化用户类型选项

    public void InitPane(){//所有Pane设为不可用
        usuallypane.setVisible(false);
        usuallypane.setDisable(true);

        extrapane.setVisible(false);
        extrapane.setDisable(true);
    }//初始化所有的pane

    public void showusuallyPane(){//教师类型的Pane设为可见可用
        usuallypane.setVisible(true);
        usuallypane.setDisable(false);
    }//展示普通界面

    public void showextraPane(){//学生类型的Pane设为不可见不可用
        extrapane.setVisible(true);
        extrapane.setDisable(false);
        gradeComboBoxPrepare();//为年级选项框准备数据
    }//显示额外界面

    public void checkUserKind(){
        String tmp = (String)userKindComboBox.getValue();
        if(tmp.equals("学生")){
            InitPane();
            showextraPane();
            extraTipText.setText("");
        }
        else if(tmp.equals("教师")){
            InitPane();
            showusuallyPane();
            usuallyTipText.setText("");
        }
    }//核实用户类型，根据用户类型的不同显示不同的界面

    public boolean CheckIDIsExist(String ID){
        User user;
        for(int i = 0;i< DataField.userData.size();i++){
            user = DataField.userData.get(i);
            if(ID.equals(user.ID)){
                return true;
            }
        }
        return false;
    }//如果ID已经注册，返回true

    public boolean CheckIDInWhitelist(String ID){
        String tmp;
        for(int i =0;i<DataField.whiteList.size();i++){
            tmp = DataField.whiteList.get(i);
            if(tmp.equals(ID)){
                return true;
            }
        }
        return false;
    }//如果ID在白名单内，返回true

    public boolean CheckTextFieldIsFinished(){
        System.out.println(IDInputTextField.getText());
        System.out.println(PWInputTextField.getText());
        System.out.println(NameInputTextField.getText());
        System.out.println(IQInputTextField.getText());
        System.out.println(IAInputTextField.getText());
        if(IDInputTextField.getText().equals("")||
                PWInputTextField.getText().equals("")||
                NameInputTextField.getText().equals("")||
                IQInputTextField.getText().equals("")||
                IAInputTextField.getText().equals("")){

            return false;
        }
        return true;
    }//如果输入框有空，返回false

    public boolean CheckUserKindFinished(){
        if(userKindComboBox.getValue() == null){
            return false;
        }
        return true;
    }//如果输入框有空，返回false

    public boolean CheckGradeAndMajorAndClassFinished(){
        if(gradeComboBox.getValue() == null ||
            majorComboBox.getValue() == null ||
            classComboBox.getValue() == null){
            return false;
        }
        return true;
    }//如果年级专业班级有空，返回false


    public void UserRegister(String ID,String PW,String Name,String Userkind,String IQ,String IA){
        User user = new User(ID,PW,Name,Userkind,IQ,IA);
        DataField.userData.add(user);
    }

    public void TeacherRegister(){
        if(CheckTextFieldIsFinished() == false){//如果没填完，无作为，如果填完，那么往下执行
            usuallyTipText.setText("请将信息填写完毕");
            return;
        }
        if(CheckUserKindFinished() == false){//如果用户类型没写，结束
            usuallyTipText.setText("请选择用户类型");
            return;
        }

        if(CheckIDIsExist(IDInputTextField.getText())){//如果这个学号注册过
            usuallyTipText.setText("本账户已注册");
            return;
        }
        if(CheckIDInWhitelist(IDInputTextField.getText()) == false){//如果不是白名单
            usuallyTipText.setText("本账户不在白名单内，请联系管理员");
            return ;
        }
        if(PWInputTextField.getText().length() == 0 || PWInputTextField.getText().length()>10){
            usuallyTipText.setText("密码长度必须为1~10个字符");
            return;
        }
        if(IQInputTextField.getText().length() == 0 || IQInputTextField.getText().length()>10){
            usuallyTipText.setText("密保问题长度必须为1~10个字符");
            return;
        }
        if(IAInputTextField.getText().length() == 0 || IAInputTextField.getText().length()>10){
            usuallyTipText.setText("密保答案长度必须为1~10个字符");
            return;
        }
        for(Teacher teacher:DataField.teacherData){//禁止同名教师出现
            if(teacher.Name.equals(NameInputTextField.getText())){
                usuallyTipText.setText("该教师名已使用，请尝试姓名+工号后四位");
                return;
            }
        }
        //注册user
        UserRegister(IDInputTextField.getText(),PWInputTextField.getText(),
                        NameInputTextField.getText(),"2",
                        IQInputTextField.getText(),IAInputTextField.getText());
        //写入user数据
        try{
            DataIO.UserWrite();
        }
        catch (IOException e){
            System.out.println("user数据写入文件失败"+e);
        }
        //注册teacher
        Teacher teacher = new Teacher(IDInputTextField.getText(),NameInputTextField.getText(),new ArrayList<String>());
        DataField.teacherData.add(teacher);
        //写入teacher数据
        try{
            DataIO.TeacherWrite();
        }
        catch (IOException e){
            System.out.println("teacher数据写入文件失败"+e);
        }
        usuallyTipText.setText("教师 "+IDInputTextField.getText()+" 注册成功");
    }

    public void StudentRegister(){
        if(CheckTextFieldIsFinished() == false){//如果没填完，无作为，如果填完，那么往下执行
            extraTipText.setText("请将信息填写完毕");
            return;
        }
        if(CheckUserKindFinished() == false){//如果用户类型没写，结束
            extraTipText.setText("请选择用户类型");
            return;
        }
        if(CheckGradeAndMajorAndClassFinished() == false){//如果是年级专业班级没写，结束
            extraTipText.setText("请完善您的年级、专业、班级信息");
            return;
        }
        if(CheckIDIsExist(IDInputTextField.getText())){//如果这个学号注册过
            extraTipText.setText("本账户已注册");
            return;
        }
        if(CheckIDInWhitelist(IDInputTextField.getText()) == false){//如果不是白名单
            extraTipText.setText("本账户不在白名单内，请联系管理员");
            return ;
        }
        if(PWInputTextField.getText().length() == 0 || PWInputTextField.getText().length()>10){
            extraTipText.setText("密码长度必须为1~10个字符");
            return;
        }
        if(IQInputTextField.getText().length() == 0 || IQInputTextField.getText().length()>10){
            extraTipText.setText("密保问题长度必须为1~10个字符");
            return;
        }
        if(IAInputTextField.getText().length() == 0 || IAInputTextField.getText().length()>10){
            extraTipText.setText("密保答案长度必须为1~10个字符");
            return;
        }
        //注册user
        UserRegister(IDInputTextField.getText(),PWInputTextField.getText(),
                NameInputTextField.getText(),"1",
                IQInputTextField.getText(),IAInputTextField.getText());
        //写入user数据
        try{
            DataIO.UserWrite();
        }
        catch (IOException e){
            System.out.println("user数据写入文件失败"+e);
        }
        //注册student
        StudentClass sc = new StudentClass((String)gradeComboBox.getValue(),(String)majorComboBox.getValue(),(String)classComboBox.getValue());
        Student student = new Student(IDInputTextField.getText(),NameInputTextField.getText(),sc);
        DataField.studentData.add(student);
        //写入student数据
        try{
            DataIO.StudentWrite();
        }
        catch (IOException e){
            System.out.println("student数据写入文件失败"+e);
        }
        extraTipText.setText("学生 "+IDInputTextField.getText()+" 注册成功");
    }

    public void gradeComboBoxPrepare(){
        gradeComboBox.getItems().clear();
        majorComboBox.getItems().clear();
        classComboBox.getItems().clear();
        gradeComboBox.getItems().addAll(DataField.gradeList);
    }

    public void gradeComboBoxOnAction(){//为majorComboBox作准备
        majorComboBox.getItems().clear();
        classComboBox.getItems().clear();
        majorComboBox.getItems().addAll(DataField.majorList);
    }

    public void majorComboBoxOnAction(){//为classComboBox作准备
        classComboBox.getItems().clear();
        //在classlist中寻找与选择的年级专业相符合的班级，添加进选项中
        if(gradeComboBox.getValue() == null || majorComboBox.getValue() == null){
            return ;//如果有选项为空，什么都不干
        }
        String grade = (String)gradeComboBox.getValue();
        String major = (String)majorComboBox.getValue();
        StudentClass sc;
        for(int i = 0;i<DataField.classList.size();i++){
            sc = DataField.classList.get(i);
            if(sc.StudentGrade.equals(grade) && sc.StudentMajor.equals(major)){//如果年级和班级都相等
                classComboBox.getItems().add(sc.StudentClass);//加入选项中
            }
        }
    }

    public void GoBack(){//返回登录界面
        CloseRegister();//关闭当前界面
        openLoginWindows();//打开登录界面
    }//返回

    public void CloseRegister(){
        Stage stage = (Stage)borderPane.getScene().getWindow();//通过布局获取场景再获取舞台
        StageManager.STAGEMAP.put("Register",stage);//保存舞台
        StageManager.CONTROLLERMAP.put("RegisterController",this);//保存控制器
        stage.close();//关闭舞台
    }//关闭当前页面

    public void openLoginWindows() {
        Stage stage = StageManager.STAGEMAP.get("Login");//读取Login的引用，打开Login界面
        StageManager.STAGEMAP.remove("Login");//在MAP中删除Login页面的Stage
        StageManager.CONTROLLERMAP.remove("Login");//在MAP中删除Login页面的Controller
        stage.show();
    }

    //标题栏最小化、关闭、拖拽
    private double oldStageX,oldStageY,oldScreenX,oldScreenY;//点击时记录窗口的XY
    //最小化
    public void MinButtonClicked(){
        Stage stage = (Stage) borderPane.getScene().getWindow();
        stage.setIconified(true);
    }//设置最小化按钮点击时发生的活动选项
    //关闭
    public void CloseButtonClicked(){
        Stage stage = (Stage) borderPane.getScene().getWindow();
        stage.close();
    }//设置关闭按钮点击时发生的活动选项
    //鼠标拖拽
    public void MousePressed(MouseEvent event){
        Stage stage = (Stage) borderPane.getScene().getWindow();
        oldStageX = stage.getX();//事件相对于MouseEvent源的原点的水平位置，即获取当前鼠标位置
        oldStageY = stage.getY();//事件相对于MouseEvent源的原点的垂直位置，即获取当前鼠标位置
        oldScreenX = event.getScreenX();//返回事件的绝对水平位置，即获取窗口左上角位置
        oldScreenY = event.getScreenY();//返回事件的绝对垂直位置，即获取窗口左上角位置
    }

    public void MouseDragged(MouseEvent event){
        Stage stage = (Stage) borderPane.getScene().getWindow();
        stage.setX(event.getScreenX()-oldScreenX+oldStageX);
        stage.setY(event.getScreenY()-oldScreenY+oldStageY);
    }


    @Override
    public void initialize(URL location, ResourceBundle resources) {
        InituserKindComboBox();
        InitPane();
        showusuallyPane();
    }
}
